package com.cskaoyan;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: bwj
 * @Date: 2022/09/09/23:55
 * @Description:
 */
@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class myTypeHandel implements TypeHandler<String[]> {
    ObjectMapper objectMapper=new ObjectMapper();

    //输入映射
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, String[] strings, JdbcType jdbcType) throws SQLException {
        String value=objectMapper.writeValueAsString(strings);
        preparedStatement.setString(i,value);
    }

    //输出映射
    @Override
    public String[] getResult(ResultSet resultSet, String s) throws SQLException {
        String result =resultSet.getString(s);
        return transfer(result);
    }

    @Override
    public String[] getResult(ResultSet resultSet, int i) throws SQLException {
        String result=resultSet.getString(i);
        return transfer(result);
    }

    @Override
    public String[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        String result = callableStatement.getString(i);
        return transfer(result);
    }

    //类型转换，自己写
    @SneakyThrows
    private String[] transfer(String result) {
        String[] strings = new String[0];
        if (result == null || "".equals(result)) {
            return strings;
        }
        strings=objectMapper.readValue(result,String[].class);
        return strings;
    }
}
